#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
////////////////////////////////////
#include <aos/aos.h>
#include <aos/yloop.h>
#include "netmgr.h"
#include "iot_export.h"
#include "iot_import.h"
#include "app_entry.h"
#include "aos/kv.h"
#include "vendor.h"
#include "device_state_manger.h"
#include "smart_outlet.h"
#include "msg_process_center.h"
#include "property_report.h"
#include "hfilop/hfilop.h"
#include "hfat_cmd.h"
#include "ymodem.h"
#include "hal/wifi.h"
#include <hal/soc/flash.h>
#include <hal/soc/gpio.h>
#include "board.h"
#include "hfilop/hfilop.h"
#include "hfilop/hfilop_config.h"

#include "business.h"
#include "cJSON.h"
#include "ugen_main.h"
#include "ugen_config.h"
#include "device_state_manger.h"


unsigned char FACTORY_TEST_FLAG = 0; //标记为1为时在执行产测2

extern int get_ugen_config_value(uint8_t *data,uint8_t len);
extern int ugen_analysis_cloude_cmd(uint8_t *data,uint8_t len);
//86400
//心跳回复
static void hertbeat_reply(void)
{
    uint8_t reply_buf[5] = {DEVICE_CMD_HEAD,0xFC,0x02,0x05,0x01};
    reply_buf[1] = check_sum(reply_buf,5);
    ugen_uart_send(reply_buf,5);
}
//上报结果回复
void ugen_up_reply(int res,uint8_t msg_type)
{
    uint8_t reply_buf[5] = {DEVICE_CMD_HEAD,0x03,0x02,UPPROPRETY,0x01};
    if(!res){
        reply_buf[4] = 0x00;//00失败；；01是成功
    }
    //reply_buf[3] = (msg_type == UPPROPRETY)?UPPROPRETY:UPEVENT;
    if(msg_type == UPEVENT){
        reply_buf[3] = UPEVENT;
    }
    reply_buf[1] = check_sum(reply_buf,5);
    ugen_uart_send(reply_buf,5);
}
static void set_property_reply(int res)
{
    if(res){
        LOG_TRACE("set success");
    }else{
        LOG_TRACE("set false");
    }
}
static void result_reply(int ret)
{
    uint8_t reply_buf[5] = {DEVICE_CMD_HEAD,0xFC,0x02,0x05,0x01};
    reply_buf[1] = check_sum(reply_buf,5);
    ugen_uart_send(reply_buf,5);
}
uint8_t ugen_get_wifi_state(void)
{
    switch (get_net_state())
    {
    
    case UNKNOW_STATE://模组启动完成
        return 1;
    case WAITINGCONFIG://模组待配网
        return 2;
    case CONNECT_CLOUD_SUCCESSED://模组已配网
        return 3;
    case UNCONFIGED://WIFI正处于配网状态，进入配网
        return 4;
    case CONNECT_CLOUD_SUCCESS://WIFI连上云端,联网成功
        return 5;
    case CONNECT_AP_FAILED://WIFI未连上路由器，配网失败
        return 6;
    case CONNECT_CLOUD_FAILED://WIFI连上路由器未连上云端，配网失败
        return 6;    
    
    default:
        break;
    }
}
//回复配网状态
void ugen_wifi_state_reply(void)
{
    uint8_t reply_buf[5] = {DEVICE_CMD_HEAD,0xFC,0x02,0x03,0x01};
    reply_buf[4] = ugen_get_wifi_state();
 
    reply_buf[1] = check_sum(reply_buf,5);
    ugen_uart_send(reply_buf,5);

    printf("check-CONNECT_CLOUD_SUCCESS\n");
    if(reply_buf[4] == 5){
        set_net_state(CONNECT_CLOUD_SUCCESSED);//配网成功，状态置为已配网；
        uint8_t state_buf[5] = {DEVICE_CMD_HEAD,0xFC,0x02,0x10,0x01};
        state_buf[1] = check_sum(state_buf,5);
        aos_msleep(200);//两条下发间隔太短，mcu无法分辨，适当进行延时；
        ugen_uart_send(state_buf,5);
    }else if(reply_buf[4] == 6){
        set_net_state(WAITINGCONFIG);//配网失败，状态置为待配网；
    }
}
//发送时间戳
static void ugen_send_timeStamp(void)
{
    uint8_t wifi_timestamp[8] = {DEVICE_CMD_HEAD,0xFC,0x05,0x06,0x00,0x00,0x00,0x00};
    uint64_t timeStamp = sync_timeStamp_tiemr_cb();
    wifi_timestamp[4]=(timeStamp&0xFF000000)>>24;
    wifi_timestamp[5]=(timeStamp&0x00FF0000)>>16;
    wifi_timestamp[6]=(timeStamp&0x0000FF00)>>8;
    wifi_timestamp[7]=(timeStamp&0x000000FF);
    wifi_timestamp[1]= check_sum(wifi_timestamp,8);

    ugen_uart_send(wifi_timestamp,8);
}
//产测
static void ugen_factory_test(uint8_t cmd)
{
    int ret = ugen_pt_start(cmd);
    if(cmd == 2)
        return;
    uint8_t factory_buf[6] = {DEVICE_CMD_HEAD,0x03,0x02,FACTORY,0x01,0x00};
    if(ret >= 0){
        factory_buf[5] = ret;
    }else{
        factory_buf[4] = 0x00;//产测失败,,0x01//产测成功
    }
    factory_buf[1] = check_sum(factory_buf,6);
    ugen_uart_send(factory_buf,6);
}
/*自检超时的判断*/
void check_is_test(void)
{
    FACTORY_TEST_FLAG = 0;
    uint8_t factory_buf[6] = {DEVICE_CMD_HEAD,0x03,0x02,FACTORY,0x01,0x00};
    factory_buf[4] = 0x00;//产测失败,0x01//产测成功
    factory_buf[1] = check_sum(factory_buf,6);
    ugen_uart_send(factory_buf,6);
    netmgr_clear_ap_config();
    aos_timer_stop(&wifi_connect_timer);
    aos_timer_free(&wifi_connect_timer);
    HAL_Reboot();
}
//网络状态查询
uint8_t search_net_state(void){
	user_example_ctx_t *user_example_ctx = user_example_get_ctx();
	LOG_TRACE("user_example_ctx cloud connected state:%d", user_example_ctx->cloud_connected);
	if (user_example_ctx->cloud_connected == 1)
        {
            LOG_TRACE("wifi_state_is_connect\n");
            return 1;
        }
        else
        {
            LOG_TRACE("wifi_state_is_not_connect\n");
            return 0;
        }
}
//初始化
static void ugen_reset_start(void)
{
    printf("reset_start\n");
    uint8_t reset_buf[5] = {DEVICE_CMD_HEAD,0xFC,0x02,0x04,0x01};
    check_sum(reset_buf,5);
    ugen_uart_send(reset_buf,5);
    lock_event_clean();
}

///////////////////////////////////////////////////////串口接收
void ugen_uart_recv_handle(uint8_t *data, uint8_t len )
{ 
    LOG_TRACE("ugen_uart_recv_handle \n");
    TRACE_BINARY(data,len);
#ifdef CHECKOPEN   
    if(data[0] != MCU_CMD_HEAD)//数据头不对结束
        return; 
    uint16_t check_s = check_sum(data, len);
    if(check_s != data[1])//校验位错误结束
        return;     
#endif
    uint8_t bath_cmd = data[3];//命令位D0 FA 02 05 01

    switch (bath_cmd)/////////////////////////////////////////命令位
    {
    case NETWORK:                          //////////////////配网
        HAL_ugen_start_ap_config();
        break;
    case GET_STATE:                      /////////////////////mcu主动查询状态
        ugen_wifi_state_reply();
        break;
    case RESET:                           ////////////////////初始化
        ugen_reset_start();
        break;
    case HEARTBEAT:                       //////////////////心跳
        hertbeat_reply();
        break;
    case UPGRAND_TIME:                     //////////////////时间校准
        ugen_send_timeStamp();
        break;   
    case FACTORY:                          //////////////////产测
        ugen_factory_test(data[4]);
        break;       
    // case CHECK_OTA:                          /////////////检测ota，不用控制从阿里云发起ota
    //     ugen_check_ota();
    //     break;
    case SETPROPRETY:                            ////////////下发属性设置回复
        set_property_reply(data[4]);
        break;
    case UPPROPRETY:                              ////////////mcu状态属性上报
        get_ugen_config_value(data,len);
        break;
    case UPEVENT:                                 ////////////mcu事件上报
        get_ugen_config_value(data,len);
        break;

    default:
        break;
    }
}
///////////////////////////云端设置下发 ////////////
//cloud recv msg handle
void ugen_cloud_recv_handle(uint8_t *data , uint8_t len)
{
	LOG_TRACE("ugen_cloud_recv_handle %s --->len %d\n",data,len);
    ugen_analysis_cloude_cmd(data,len);
    return ;
}
/////////aaaaaaaaaaaaaaaaaa


